//
//  MTClubRichListViewCell.swift
//  MT
//
//  Created by ooops on 2019/12/25.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory
import RxSwift
import RxCocoa
import Kingfisher

protocol MTClubRichListViewCellDelegate: NSObjectProtocol {
    func joinClub(cell: MTClubRichListViewCell, model: MTClubRichListResultModel?)
}

class MTClubRichListViewCell: UITableViewCell {
    
    weak var delegate: MTClubRichListViewCellDelegate?
    
    //private var downLoadTasks: [Observable<DownloadTask>] = []
    
    class func reuseIdentity() -> String {
        return "MTClubRichListViewCellID"
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        avatorImageView.image = UIImage(named: defaultPlaceholderIcon60x60)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
        makeConstraint()
        backgroundColor = UIColor.theme.background
        selectionStyle = .none
        //avatorGroupView.imgList = [UIImage(named: "placeholder-square")!]
    }
    
    /* 没有缓存的俱乐部头像的时候
    * 俱乐部头像缓存更新策略
    * 只有增加成员的情况下更新头像
    *
    */
//    private func downImage(target: JMSGGroup) {
//        MTGroupImageDownLoadTool.downImage(target) { [weak self] (images) in
//            guard let weakSelf = self else { return }
//            var resultImage: UIImage = UIImage(named: "placeholder-square")!
//            DispatchQueue.main.async {
//                self?.avatorGroupView.imgList = images
//            }
////            if images.count > 0 {
////                resultImage = MTWeChatAvatorTool.stitchImage(images: images, size: CGSize(width: 200, height: 200), backgroundColor: UIColor.clear, gap: 0)
////                KingfisherManager.shared.cache.store(resultImage, forKey: target.gid)
////                DispatchQueue.main.async {
////                    weakSelf.avatorImageView.image = resultImage
////                }
////
////            } else {
////                DispatchQueue.main.async {
////                    weakSelf.avatorImageView.image = resultImage
////                }
////            }
//        }
//    }
    
    
    /// 根据俱乐部id 获取俱乐部信息
//    var gid: String? {
//        didSet {
//            if gid != nil {
//                JMSGGroup.groupInfo(withGroupId: gid!, completionHandler: { (result, error) in
//                    if error == nil, let group = result as? JMSGGroup {
//                        debugPrint("group name:", group.name, "group avator:", group.avatar)
//                        group.thumbAvatarData { (data, s, e) in
//                            if let data = data {
//                                self.avatorImageView.image = UIImage(data: data)
//                            } else {
//                                self.avatorImageView.image = UIImage(named: "placeholder-square")
//                            }
//                        }
////                        let a = group.avatar
////                        let d = ""
////                        self.downImage(target: group)
//                        /// 如果存在缓存的群组头像则使用已经存在的
////                        KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: group.gid, options: [.onlyFromCache]) { [weak self] (result: Result<KFCrossPlatformImage?, KingfisherError>) in
////                            guard let weakSelf = self else { return }
////                            switch result {
////                            case .success(let image):
////                                if image == nil {
////                                    weakSelf.downImage(target: group)
////                                } else {
////                                    DispatchQueue.main.async {
////                                        weakSelf.avatorImageView.image = image
////                                    }
////                                }
////                            case .failure(_):
////                                DispatchQueue.main.async {
////                                    weakSelf.downImage(target: group)
////                                }
////                            }
////                        }
//                    }
//                })
//            }
//
//        }
//    }
    
    var conversation: JMSGConversation? {
        didSet {
            /// 消息类型提示
            if let con = conversation, let messageType: JMSGContentType = con.latestMessage?.contentType {
                let isGroup = con.ex.isGroup
                
                var redpacketTips = ""
                if con.ex.isGroup {
                    if let group = con.target as? JMSGGroup {
                        if let desc = group.desc {
                            if !desc.contains("|.>p_t_g<.|") {
                                redpacketTips = "往俱乐部里撒了"
                            } else {
                                redpacketTips = "往聚会任务群里撒了"
                            }
                        }
                    }
                }
                
                if messageType == .custom {
                    let content: JMSGCustomContent = con.latestMessage?.content as! JMSGCustomContent
                    switch content.customMsgType() {
                    case .gift, .pullGift, .giftnotify:
                        sendGiftCountLabel.text = "[礼物]"
                    case .redpack:
                        var msgText = "", conversationTypeString = ""
                        if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any>, con.latestMessage?.fromUser.isEqual(to: JMSGUser.myInfo()) == false {
                            if let conversationType: Int = dict["targetType"] as? Int {
                                conversationTypeString = conversationType == 1 ? "向你撒了" : conversationType == 2 ? redpacketTips : "往广场撒了"
                            }
                            if let redpackC: Int = dict["money"] as? Int {
                                
                                let unredCount: String = con.unreadCount?.intValue ?? 0 > 1 ? "[\(con.unreadCount!.stringValue)条]" : ""
                                
                                if isGroup {
                                    if let latestMessage = con.latestMessage {
                                        let fromUser = latestMessage.fromUser
                                        if !fromUser.isEqual(to: JMSGUser.myInfo()) &&
                                            latestMessage.contentType != .eventNotification &&
                                            latestMessage.contentType != .prompt {
                                            msgText = "\(unredCount)\(con.latestMessage!.fromUser.displayName())\(conversationTypeString)\(redpackC)钻石"
                                        }
                                    }
                                } else {
                                    msgText = "\(conversationTypeString)\(redpackC)钻石"
                                }
                                
                                sendGiftCountLabel.text = msgText
                                //clubMessageLabel.textColor = UIColor.text.xfed600
                                sendGiftCountLabel.textColor = UIColor.text.x999999
                            }
                            
                        } else {
                            sendGiftCountLabel.text = "[红包]"
                            sendGiftCountLabel.textColor = .red
                        }
                    case .pullNotify:
                        if let infos : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                            if let senderUserName: String = infos["senderUserName"] as? String,
                                let pullNickname: String = infos["pullNickname"] as? String,
                                let senderNickname: String = infos["senderNickname"] as? String {
                                
                                let isSelf: Bool = (senderUserName == JMSGUser.myInfo().username)
                                /// 如果是自己发的红包
                                if isSelf {
                                    if let pullUserName = infos["pullUserName"] as? String {
                                        /// 自己领取了自己发的红包
                                        if senderUserName == pullUserName {
                                            sendGiftCountLabel.text = "你领取了自己发的红包"
                                            sendGiftCountLabel.textColor = UIColor.text.x999999
                                        } else {
                                            sendGiftCountLabel.text = "\(pullNickname)领取了你的红包"
                                            sendGiftCountLabel.textColor = UIColor.text.x999999
                                        }
                                    } else {
                                       sendGiftCountLabel.text = "\(pullNickname)领取了你的红包"
                                        sendGiftCountLabel.textColor = UIColor.text.x999999
                                    }
                                } else {
                                   /// 不是自己发的红包
                                   if let pullUserName = infos["pullUserName"] as? String {
                                       /// 是自己领取的
                                       if JMSGUser.myInfo().username == pullUserName {
                                           sendGiftCountLabel.text = " 你领取了\(senderNickname)的红包"
                                           sendGiftCountLabel.textColor = UIColor.text.x999999
                                       } else {
                                           sendGiftCountLabel.text = "\(pullNickname)领取了\(senderNickname)的红包"
                                           sendGiftCountLabel.textColor = UIColor.text.x999999
                                       }
                                   }
                               }
                            }
                        }
                    case .activity:
                        if let infos : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                            //"[\"activityId\": 55, \"sendUserHeadUrl\": 龟虽寿, \"sendUserNickname\": mitu_2tYyu3Hp, \"messageType\": activity, \"activityInfo\": 大家老残门口可能不会沟沟壑壑哈哈哈哈哈哈哈哈哈, \"activityName\": 宝贝好]"
                            
                            if isGroup {
                                let unredCount: String = con.unreadCount?.intValue ?? 0 > 1 ? "[\(con.unreadCount!.stringValue)条]" : ""
                                if let activityName = infos["activityName"] as? String {
                                    if let latestMessage = con.latestMessage {
                                        let fromUser = latestMessage.fromUser
                                        if latestMessage.contentType != .eventNotification &&
                                            latestMessage.contentType != .prompt {
                                            if !fromUser.isEqual(to: JMSGUser.myInfo()) {
                                                sendGiftCountLabel.textColor = UIColor.text.x999999
                                                sendGiftCountLabel.text = "\(unredCount)\(con.latestMessage!.fromUser.displayName())发起了\"\(activityName)\"[活动]"
                                            } else {
                                                sendGiftCountLabel.textColor = UIColor.text.x999999
                                                sendGiftCountLabel.text = "\(unredCount)你发起了\"\(activityName)\"[活动]"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    case .task:
                    if let infos : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                        sendGiftCountLabel.textColor = UIColor.text.x999999
                        if let name = infos["partyName"] as? String, let money = infos["partyGiftNum"] {
                            sendGiftCountLabel.text = "[" + name + "] 聚会任务"
                        }
                    }
                    default:
                        break
                    }
                } else {
                    if isGroup {
                        if let latestMessage = con.latestMessage {
                            let fromUser = latestMessage.fromUser
                            if !fromUser.isEqual(to: JMSGUser.myInfo()) &&
                                latestMessage.contentType != .eventNotification &&
                                latestMessage.contentType != .prompt {
                                let unredCount: String = con.unreadCount?.intValue ?? 0 > 1 ? "[\(con.unreadCount!.stringValue)条]" : ""
                                sendGiftCountLabel.text = "\(unredCount)\(fromUser.displayName()): \(con.latestMessageContentText())"
    //                            msgLabel.text = "\(fromUser.displayName()): \(conversation.latestMessageContentText())"
                            } else {
                                var infomation = con.latestMessageContentText()
                                infomation = infomation.replacingOccurrences(of: "群聊", with: "俱乐部")
                                infomation = infomation.replacingOccurrences(of: "群", with: "俱乐部")
                                infomation = infomation.replacingOccurrences(of: ",", with: "、")
                                infomation = infomation.replacingOccurrences(of: "，", with: "、")
                                sendGiftCountLabel.text = infomation.trim(trimNewline: true)
                                sendGiftCountLabel.textColor = UIColor.text.x999999
                            }
                            
                            if con.unreadCount != nil &&
                                con.unreadCount!.intValue > 0 &&
                                latestMessage.contentType != .prompt {
                                if latestMessage.isAtAll() {
                                    sendGiftCountLabel.attributedText = getAttributString(attributString: "[@所有人]", string: sendGiftCountLabel.text!)
                                } else if latestMessage.isAtMe() {
                                    sendGiftCountLabel.attributedText = getAttributString(attributString: "[有人@我]", string: sendGiftCountLabel.text!)
                                }
                            }
                        } else {
                            sendGiftCountLabel.text = ""
                        }
                    } else {
                        let infomation = con.latestMessageContentText()
                        sendGiftCountLabel.text = infomation.trim(trimNewline: true)
                        sendGiftCountLabel.textColor = UIColor.text.x999999
                    }
                }
            }
        }
    }
    
    func getAttributString(attributString: String, string: String) -> NSMutableAttributedString {
        let attr = NSMutableAttributedString(string: "")
        var attrSearchString: NSAttributedString!
        attrSearchString = NSAttributedString(string: attributString, attributes: [NSAttributedString.Key.foregroundColor : UIColor(hex: 0xf9f9f9),
                                                                                   NSAttributedString.Key.font : PingFangSCRegularFont(12)])
        attr.append(attrSearchString)
        attr.append(NSAttributedString(string: string))
        return attr
    }
    
    var model: MTClubRichListResultModel? {
        didSet {
            clubNameLabel.text = model?.name
            
            if let n = model?.number, n <= 2 {
                NoNumberLabel.isHidden = false
                NoNumberLabel.text = n == 0 ? "No.1" : n == 1 ? "No.2" : "No.3"
                NoNumberLabel.backgroundColor = n == 0 ? UIColor(hex: 0xe3ca7d) : n == 1 ? UIColor(hex: 0xbdbdbd) : UIColor(hex: 0xd1b29f)
            } else {
                NoNumberLabel.isHidden = true
            }
            
            if let href = model?.href {
                avatorImageView.mtSetImage(href, defaultPlaceholderIcon60x60)
            }
//            if let exportMoney = model?.exportMoney {
//                clubMessageLabel.text = "累计发送\(exportMoney)钻石"
//            }
            
            if let redPacketNum = model?.redPacketNum {
                sendGiftCountLabel.text = "每日礼物 x \(redPacketNum)"
            }
            
            if let redPacketCount = model?.redPacketMoney {
                //totalGiftCountLabel.text = "\(redPacketCount)"
                setAttributeAmount(redPacketCount: redPacketCount)
            }
        }
    }
    
    private func setAttributeAmount(redPacketCount: Int) {
        let countString = Double(redPacketCount) / 10000.0
        let attributeString = NSMutableAttributedString(string: String(format: "%.1f", countString) + "万", attributes: [NSAttributedString.Key.font : PingFangSCSemiboldFont(12), NSMutableAttributedString.Key.foregroundColor : UIColor.text.x1d1a1a])
        
        let attribute1 = NSAttributedString(string: " x ", attributes: [NSAttributedString.Key.font : PingFangSCSemiboldFont(10), NSAttributedString.Key.foregroundColor : UIColor.text.x1d1a1a])
        
        attributeString.insert(attribute1, at: 0)
        
        totalGiftCountLabel.attributedText = attributeString
    }
    
    private func setupUI() {
        contentView.addSubview(avatorImageView)
        contentView.addSubview(clubNameLabel)
        contentView.addSubview(sendGiftCountLabel)
        
        contentView.addSubview(totalGiftCountTipLabel)
        contentView.addSubview(totalGiftImageView)
        contentView.addSubview(totalGiftCountLabel)
        
        contentView.addSubview(lineView)
        
        contentView.addSubview(NoNumberLabel)
    }
    
    private func makeConstraint() {
        avatorImageView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.width.height.equalTo(44)
        }
        clubNameLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(contentView.snp.centerY).offset(-2)
            make.left.equalTo(avatorImageView.snp.right).offset(16)
        }
        
        sendGiftCountLabel.snp.makeConstraints { (make) in
            make.height.left.equalTo(clubNameLabel)
            make.top.equalTo(contentView.snp.centerY).offset(2)
            //make.right.equalTo(clubAreaAndTotalLabel.snp.left).offset(-24)
        }
        
        totalGiftCountTipLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(clubNameLabel)
            make.right.equalToSuperview().offset(-10)
        }
        
        totalGiftImageView.snp.makeConstraints { (make) in
            make.centerY.equalTo(totalGiftCountLabel)
            make.right.equalTo(totalGiftCountLabel.snp.left).offset(-1)
            make.width.height.equalTo(14)
        }
        
        totalGiftCountLabel.snp.makeConstraints { (make) in
            make.top.equalTo(totalGiftCountTipLabel.snp.bottom).offset(9)
            make.right.equalTo(totalGiftCountTipLabel)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        NoNumberLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(clubNameLabel)
            make.left.equalTo(clubNameLabel.snp.right).offset(10)
            make.height.equalTo(17)
            make.width.equalTo(35)
        }
    }
    
    
    /// 图片组
//    lazy var avatorGroupView: MTClubAvatorGroupView = {
//        let v = MTClubAvatorGroupView(frame: .zero, imgList: nil)
//        return v
//    }()
    
    
    lazy var avatorImageView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.cornerRadius = 22
        imageV.layer.masksToBounds = true
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        imageV.image = UIImage(named: defaultPlaceholderIcon60x60)
        return imageV
    }()
    
    lazy var clubNameLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        return l
    }()
    
    lazy var sendGiftCountLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x9b9b9b
        l.text = ""
        l.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return l
    }()
    
    lazy var totalGiftCountTipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(10)
        l.textColor = UIColor.text.x9b9b9b
        l.text = "已累计送出"
        l.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return l
    }()
    
    lazy var totalGiftImageView: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "club_gift"))
        return imageV
    }()
    
    lazy var totalGiftCountLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x9b9b9b
        l.text = "x 222万"
        l.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return l
    }()
    
//    lazy var clubAreaAndTotalLabel: UILabel = {
//        let l = UILabel()
//        l.font = PingFangSCRegularFont(12)
//        l.textColor = UIColor.redpack.x5d5d5d
//        l.text = ""
//        l.setContentHuggingPriority(.defaultLow, for: .horizontal)
//        l.textAlignment = .right
//        return l
//    }()
    
    lazy var joinClubButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("加入", for: .normal)
        btn.addTarget(self, action: #selector(joinClub), for: .touchUpInside)
        btn.setTitleColor(.black, for: .normal)
        btn.backgroundColor = UIColor.theme.main
        btn.titleLabel?.font = PingFangSCRegularFont(14)
        btn.layer.cornerRadius = 3
        btn.layer.masksToBounds = true
        return btn
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        return v
    }()
    
    lazy var NoNumberLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(12)
        l.textColor = .white
        l.layer.cornerRadius = 2
        l.layer.masksToBounds = true
        l.text = "No.1"
        l.textAlignment = .center
        return l
    }()
    
    @objc private func joinClub() {
        
        self.delegate?.joinClub(cell: self, model: self.model)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
